import { defineStore } from 'pinia';
import { reactive } from 'vue';
import { getRightData } from '@/api/earlyWarning';
import { AlertOverview } from '@/constants/components/alertOverview';
import { mapBackendData, type moduleInfo } from '@/utils/mapBackendData';
import { useCesiumPoints } from '@/hooks/useCesiumPoints';
import componentsTitle from '@/constants/components/componentsTitle';
import { useDialogStore } from '@/store/modules/useDialogStore';
import icon from '@/assets/largescreen/yujing-mokuai.png';

interface IAlarmInfos {
  total: number;
  potencyAlarmNum: number;
  pressureAlarmNum: number;
  flowAlarmNum: number;
  normallyOpenAlarmNum: number;
  thirdAlarmNum: number;
  echartsData: any;
}

export const useAlertOverviewStore = defineStore('alertOverview', () => {
  const waringStatisticsData = ref(<IAlarmInfos>{});
  const waringList = ref<moduleInfo[]>(AlertOverview);
  const { addPoint, clearAllPoints } = useCesiumPoints();
  const dataSources = reactive<Record<string, any[]>>({});
  const { openDialog } = useDialogStore();
  const currentActiveNames = ref<string>('');
  const { flyTo } = useDialogStore();
  const alertOverviewList = ref({
    '已处置': {
      id: 1,
      name: '已处置',
      icon,
      list: []
    },
    '待处置': {
      id: 2,
      name: '待处置',
      icon,
      list: []
    },
    '处置中': {
      id: 3,
      name: '处置中',
      icon,
      list: []
    }
  });
  //饼图点击事件
  const thirdGeneralClick = (item: moduleInfo) => {
    flyTo({ longitude: 117.140035075, latitude: 36.798747059 }, 400000);
    if (dataSources[item.name]) {
      clearAllPoints(dataSources[item.name]);
      delete dataSources[item.name];
    } else {
      openDialog('alertOverviewModule');
      alertOverviewList.value[item.name].list = item.data.clickData;
      currentActiveNames.value = item.name;
      dataSources[item.name] = item.data.clickData.map((point) => addPoint(point, componentsTitle.ALERT_OVERVIEW));
    }
  };
  const initClearPoints = () => {
    Object.keys(dataSources).forEach((key) => {
      clearAllPoints(dataSources[key]);
    });
  };
  
  // 初始化警告统计数据
  const initWarningStatistics = async () => {
    const { data } = await getRightData({ type: 'waringStatistics' });
    waringStatisticsData.value = data.waringStatistics;
    waringList.value = mapBackendData(AlertOverview, data.waringStatistics, {
      '预警总数': { countKey: 'total' },
      '处置率': { countKey: 'disposalRate' }
    });
  };
  
  return {
    waringStatisticsData,
    waringList,
    alertOverviewList,
    currentActiveNames,
    thirdGeneralClick,
    initClearPoints,
    initWarningStatistics
  };
});
